package com.simba.system.service;

import com.simba.system.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
@Component
public class OceanUserDetailService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public User loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByUsername(username);
        if (null != user) {
            user.setRoles(userService.getRoles(user.getUserId()));
            return user;
        }
        throw new UsernameNotFoundException("用户不存在，请联系管理员！");
    }

    /**
     * * 获取用户的角色权限,为了降低实验的难度，这里去掉了根据用户名获取角色的步骤
     * * @param
     * * @return
     */
    private Collection<GrantedAuthority> getAuthorities(String username) {
        log.info("进入了OceanUserDetailService中的getAuthorities方法");
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
        authList.add(new SimpleGrantedAuthority("ROLE_admin"));
        return authList;
    }
}
